package cn.gok.web;

import cn.gok.entity.MaintainDormitory;
import cn.gok.entity.Student;
import cn.gok.service.IMaintainDormitoryService;
import cn.gok.service.impl.MaintainDormitoryServiceImpl;
import cn.gok.util.MapObjectMapper;
import cn.gok.util.R;
import cn.hutool.json.JSONUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileItemHeaders;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.ibatis.logging.stdout.StdOutImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

/**
 * @Author: chen fan
 * @Date: 2022/3/11 11:08
 * @Description:
 */
@WebServlet("/maintainDormitoryServlet")
public class MaintainDormitoryServlet extends HttpServlet {

    private IMaintainDormitoryService  maintainDormitoryService = new MaintainDormitoryServiceImpl();

    //定义一个集合存储图片的后缀的格式
    private static List<String> imgSuffixes = new ArrayList<>();
    static {
        imgSuffixes.add(".png");
        imgSuffixes.add(".jpg");
        imgSuffixes.add(".jpeg");
        imgSuffixes.add(".gif");
        imgSuffixes.add(".bmp");
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getParameter("action");
        switch (action){
            case "addMaintainDormitory": addMaintainDormitory(req, resp);break;
            case "queryMaintainDormitories": queryMaintainDormitories(req,resp);break;
        }
    }


    public void queryMaintainDormitories(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setHeader("Content-type", "application/json;charset=utf-8");
        resp.setContentType("application/json;charset=utf-8");

        int stuId = ((Student)req.getSession().getAttribute("student")).getStuId();
        int state = Integer.parseInt(req.getParameter("state"));
        int currPage = Integer.parseInt(req.getParameter("currPage"));
        int pageSize = Integer.parseInt(req.getParameter("pageSize"));

        R r = maintainDormitoryService.queryMaintainDormitories(stuId, state, currPage, pageSize);

        resp.getWriter().println(JSONUtil.toJsonStr(r));
    }
    /**
     * 学生添加报修信息
     */
    public void addMaintainDormitory(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        //获取commons.fileupload 工具提供工厂对象
        FileItemFactory factory = new DiskFileItemFactory();

        //根据工厂对象获取一个文件上传的 fileUpload对象
        ServletFileUpload fileUpload = new ServletFileUpload(factory);

        //限制上传文件的大小
        fileUpload.setSizeMax(1024*1024*5);

        //解析request请求：request请求中既有字符串数据，又有上传的多媒体文件数据（.text, .png .jpg .mp4）,
        Map<String, List<FileItem>> parameterMap = null;
        try {

            /*
              1、 parseParameterMap方法解析request
                  得到 Map<String, List<FileItem>>
                        key ： input表单中的name值
                        FileItem：  表示表单数据，它既可能是字符串数据也可能是多媒体文件数据，
                                    我们可以通过它提供的方法isFormField() 进行判它到底是什么数据

                        List<FileItem> ：会出现多个input用同一个name的情况，
                                        比如复选框，或者一个主图、多个副图这种情况
             */
            parameterMap = fileUpload.parseParameterMap(req);


            //获取宿舍报修文本信息
            List<FileItem> fileItems = parameterMap.get("desc");
            String desc = new String(fileItems.get(0).get(),"utf-8");

            //获取宿舍报修上传的图片
            List<FileItem> fileItems1 = parameterMap.get("file");
            FileItem fileItem = fileItems1.get(0);


            //2、判断用户提交的是否为图片
            //2.1、获取图片的名字  比如 xxxx.png
            String name = fileItem.getName();
            //2.2 获取图片的后缀名
            String imgSuffix = name.substring(name.lastIndexOf("."));

            //判断是否为图片, 即判断后缀名  在 imgSuffixes集合中是否存在
            if (!imgSuffixes.contains(imgSuffix) ){
                resp.getWriter().println(JSONUtil.toJsonStr(R.fail("提交失败，请上传正确的图片格式")));
                return;
            }

            //3、重新生成图片名
            String newImageName = UUID.randomUUID().toString() + imgSuffix;

            //4、生成图片存储的路径

            //获取当前项目的根路径
            String contextPath = req.getSession().getServletContext().getRealPath("");

            //创建出图片的存储路径,比如 /dormitorySystem/image/
            File file = new File(contextPath + File.separator +"maintainDormitoryImage");

            //如果文件夹不存在，则创建
            if(!file.exists()){
                file.mkdirs();
            }
            //5、将图片通过输出流输出指定的路径
            fileItem.write(new File(contextPath +
                    File.separator +"maintainDormitoryImage"+ File.separator + newImageName));

            //6、将基本信息存入数据库
            MaintainDormitory maintainDormitory = new MaintainDormitory();

            Integer stuId = ((Student) req.getSession().getAttribute("student")).getStuId();
            maintainDormitory.setId(stuId);
            maintainDormitory.setDorId( 1 );
            maintainDormitory.setDesc(desc);
            maintainDormitory.setImageUrl(newImageName);
            maintainDormitory.setCreateTime(new Date());

            R r = maintainDormitoryService.addMaintainDormitoryInfo(maintainDormitory);
            resp.getWriter().println(JSONUtil.toJsonStr(r));

        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
